from flask import Blueprint, render_template, flash, redirect, url_for, request, jsonify, session
from flask_login import current_user, login_required

from apps.forms.image_library_form import QueryImageLibraryForm, CreateImageLibraryForm, UpdateImageLibraryForm
from common.json_util import to_dicts
from rules.image_library_rule import search_image_library_with_page, create_image_library, search_image_library, \
    describe_image_library, search_image_library_with_list

image_library = Blueprint('image_library', __name__, url_prefix='/image_library')
ACTIVE = 'library'
ACTIVE_ITEM = 'image_library'
SEARCH_PAGE = 'image_library_page'


@image_library.route('/page', methods=['POST', 'GET'])
@login_required
def page():
    form = QueryImageLibraryForm(csrf_enabled=False)
    last_search = session.get('last_search')
    page_index = 1
    title = ''
    dy_open_pic_id = ''

    if request.method == 'GET':
        if last_search and last_search.get('search_page', '') == SEARCH_PAGE:
            # page_index = last_search.get('page_index', 1)
            if last_search.get('search_data'):
                title = last_search.get('search_data').get('title', '')
                dy_open_pic_id = last_search.get('search_data').get('dy_open_pic_id', '')

        page_index = request.args.get('page', page_index, type=int)

        title = request.args.get('title', title)
        dy_open_pic_id = request.args.get('dy_open_pic_id', dy_open_pic_id)

        form.title.data = title
        form.dy_open_pic_id.data = dy_open_pic_id

    else:
        page_index = 1
        if form.title.data:
            title = form.title.data

        if form.dy_open_pic_id.data:
            dy_open_pic_id = form.dy_open_pic_id.data

    search_data = dict(title=title, dy_open_pic_id=dy_open_pic_id)
    last_search = dict(search_page=SEARCH_PAGE, page_index=page_index, search_data=search_data)
    session['last_search'] = last_search

    print(last_search)

    pagination = search_image_library_with_page(page_index, search_data)

    return render_template('image_library/page.html', pagination=pagination, form=form, active=ACTIVE,
                           active_item=ACTIVE_ITEM)


@image_library.route('/create', methods=['POST', 'GET'])
@login_required
def create():
    form = CreateImageLibraryForm()
    if form.validate_on_submit():
        create_image_library(form, current_user)
        flash('新增成功', 'page_success')
        return redirect(url_for('image_library.page'))
    return render_template('image_library/create.html', form=form, active=ACTIVE,
                           active_item=ACTIVE_ITEM)


@image_library.route('/edit/<int:id>', methods=['POST', 'GET'])
@login_required
def edit(id):
    image_library_orm = search_image_library(id)
    if not image_library_orm:
        return redirect(url_for('image_library.page'))

    if request.method == 'GET':
        form = UpdateImageLibraryForm(image_library_orm)
    else:
        form = UpdateImageLibraryForm()

    if form.validate_on_submit():
        try:
            describe_image_library(id, form, current_user)
            flash('修改成功', 'page_success')
            return redirect(url_for('image_library.page'))
        except Exception as e:
            flash(str(e), 'page_error')

    return render_template('image_library/edit.html', form=form, id=id, active=ACTIVE,
                           active_item=ACTIVE_ITEM)



@image_library.route('/list/<keyword>', methods=['GET'])
@login_required
def search_list(keyword):
    try:
        data_param = dict(title=keyword)
        image_list = search_image_library_with_list(data_param)
    except Exception as e:
        image_list = []

    return jsonify({"status": 'success', "msg": '', "data": image_list})